package com.hanxiaozhang.threadbase1ndedition.no5juccommonclass;

import java.util.concurrent.CountDownLatch;

/**
 * 〈一句话功能简述〉<br>
 * 〈CountdownLatch 门闩，闭锁〉
 * <p>
 * 概念：
 * 它可以使一个线程等待其他线程完成各自的工作后再执行。
 * <p>
 * 常见方法：
 * CountDownLatch(int count)：构造函数，count（计数值）是闭锁需要等待的线程数量；
 * await()：使当前线程等待，直到锁存器计数为零；
 * await(long timeout, TimeUnit unit)：使当前线程等待，直到锁存器计数为零，或者超过指定的等待时间；
 * countDown()：减少闩锁的计数，即调用一次count值减1。如果count等于0时，释放所有等待的线程；
 * getCount()：获取count值，即现在闭锁需要等待的线程数量。
 *
 * @author hanxinghua
 * @create 2021/11/14
 * @since 1.0.0
 */
public class No2CountDownLatch {

    public static void main(String[] args) {
        usingJoin();
        usingCountDownLatch();
    }

    /**
     * 使用CountDownLatch类
     */
    private static void usingCountDownLatch() {
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                int result = 0;
                for (int j = 0; j < 10000; j++) {
                    result += j;
                }
                latch.countDown();
            });
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("end latch");
    }


    /**
     * 使用join方法
     */
    private static void usingJoin() {
        Thread[] threads = new Thread[100];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                int result = 0;
                for (int j = 0; j < 10000; j++) {
                    result += j;
                }
            });
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("end join");
    }

}
